package com.baosight.risk.service.riri.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.stream.Collectors;

import com.baosight.risk.api.workflow.BeforeHandler;
import com.baosight.risk.mapper.riri.xml.RiriImpRiskMapper;
import com.baosight.risk.mapper.riri.xml.RiriYyRiskMapper;
import com.baosight.risk.service.fltd.entity.FltdProcess;
import com.baosight.risk.service.riri.entity.RiriImpRisk;
import com.baosight.risk.service.riri.entity.RiriYyRisk;
import com.baosight.risk.service.riri.vo.RiRiRiskDetailParamVO;
import com.baosight.risk.service.xtzy.vo.XtzyUserVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.fltd.FltdTaskService;
import com.baosight.risk.api.riri.IRiriRiskService;
import com.baosight.risk.api.workflow.UpdateHandler;
import com.baosight.risk.api.xtaa.code.IXtaaCodeService;
import com.baosight.risk.api.xtaa.sequences.IXtaaSequencesService;
import com.baosight.risk.base.redis.BaseRedis;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.aspects.factory.AsyncFactory;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.manager.AsyncManager;
import com.baosight.risk.common.utils.DateUtils;
import com.baosight.risk.common.utils.ShiroUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.quartz.SysJobParamMapper;
import com.baosight.risk.mapper.riim.RiimRiskImportMapper;
import com.baosight.risk.mapper.riri.RiriRiskHisMapper;
import com.baosight.risk.mapper.riri.RiriRiskMapper;
import com.baosight.risk.mapper.xtzy.XtzyCompanyMapper;
import com.baosight.risk.mapper.xtzy.XtzyRoleUserMapper;
import com.baosight.risk.mapper.xtzy.XtzyUserMapper;
import com.baosight.risk.service.fltd.entity.FltdTask;
import com.baosight.risk.service.fltd.vo.FltdTaskVO;
import com.baosight.risk.service.riim.entity.RiimRiskImport;
import com.baosight.risk.service.riri.entity.RiriRisk;
import com.baosight.risk.service.riri.entity.RiriRiskHis;
import com.baosight.risk.service.riri.vo.RiRiRiskDetailVO;
import com.baosight.risk.service.riri.vo.RiriRiskVO;
import com.baosight.risk.service.riri.vo.RiskTopThreeVO;
import com.baosight.risk.service.system.entity.SysOperLog;
import com.baosight.risk.service.xtaa.code.entity.XtaaCode;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import com.baosight.risk.service.xtzy.impl.XtzyCompanyServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import lombok.extern.slf4j.Slf4j;

/**
 * 类 名: RiriRiskServiceImpl
 * 描 述:
 * 作 者: 黎秋荣
 * 创 建：2019年05月08日
 * 版 本：v2.2.0
 * 历 史: (版本) 作者 时间 注释
 */
@Service
@Slf4j
public class RiriRiskServiceImpl extends BaseServiceImpl<RiriRisk> implements IRiriRiskService, UpdateHandler , BeforeHandler {

    @Autowired
    private RiriRiskMapper ririRiskMapper;

    @Autowired
    private RiriImpRiskMapper ririImpRiskMapper;

    @Autowired
    private RiriYyRiskMapper ririYyRiskMapper;

    @Autowired
    private XtzyUserMapper userMapper;

    @Autowired
    private RiriRiskHisMapper ririRiskHisMapper;

    @Autowired
    private IXtaaSequencesService sequencesService;

    @Autowired
    private RiaaRiskServiceImpl riaaRiskService;

    @Autowired
    private XtzyCompanyMapper companyMapper;
    @Autowired
    private XtzyCompanyServiceImpl xtzyCompanyService;

    @Autowired
    private FltdProcessService fltdProcessService;

    @Autowired
    private FltdTaskService fltdTaskService;

    @Autowired
    private IXtaaCodeService xtaaCodeService;

    @Autowired
    private BaseRedis baseRedis;

    @Autowired
    private XtzyRoleUserMapper xtzyRoleUserMapper;

    @Autowired
    private RiimRiskImportMapper riskImportMapper;

    @Autowired
    private SysJobParamMapper sysJobParamMapper;

    @Override
    public List<RiriRisk> selectRiriRisk(RiriRiskVO ririRisk, XtzyUser user) {
        //userCode    ext1:编号   ext2:宝钢股份
        List<RiriRisk> list = Lists.newArrayList();
        if (user != null&&StringUtils.isEmpty(ririRisk.getDeptCode())){
            //扩展字段5代表当前登陆人的全部角色编码
            if(user.getExt5().contains("RISK") || "admin".equals(user.getUserCode())){
               boolean flag= xtzyCompanyService.checkManageCompCode(ririRisk.getManageCompCode(),user.getManageCompCode());
                if(flag){

                }else{
                    ririRisk.setDeptCode(user.getExt1());
                }
            }else{
                ririRisk.setDeptCode(user.getExt1());
            }
        }
        RiriRiskVO riskVO = getRiskVo(ririRisk, user);
        servicePage();
        list = ririRiskMapper.selectRiriRisk(riskVO);
        // 默认排序
        if (BeanUtils.sortList(list)) {
            for (RiriRisk risk : list) {
                RiriRisk param = new RiriRisk();
                param.setId(risk.getId());
                param.setRowOrder(risk.getRowOrder());
                ririRiskMapper.updateByPrimaryKeySelective(param);
            }
        }

        if ("flag".equals(riskVO.getExt3())) {
            list = list.stream().collect(Collectors.collectingAndThen(
                    Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(RiriRisk::getRiskNo))
                    ), ArrayList::new));
        }
        return list;
    }

    @Override
    public List<RiriRisk> selectPredictRiriRisk(RiriRiskVO ririRisk, XtzyUser user) {
        //userCode    ext1:编号   ext2:宝钢股份
        List<RiriRisk> list = Lists.newArrayList();
        if (user != null){
            //扩展字段5代表当前登陆人的全部角色编码
            if(user.getExt5().contains("RISK") || "admin".equals(user.getUserCode())){
                boolean flag= xtzyCompanyService.checkManageCompCode(ririRisk.getManageCompCode(),user.getManageCompCode());
                if(flag){

                }else{
                    ririRisk.setDeptCode(user.getExt1());
                }
            }else{
                ririRisk.setDeptCode(user.getExt1());
            }
        }
        RiriRiskVO riskVO = getRiskVo(ririRisk, user);
        servicePage();
        list = ririRiskMapper.selectRiriRisk(riskVO);
        // 默认排序
        if (BeanUtils.sortList(list)) {
            for (RiriRisk risk : list) {
                RiriRisk param = new RiriRisk();
                param.setId(risk.getId());
                param.setRowOrder(risk.getRowOrder());
                ririRiskMapper.updateByPrimaryKeySelective(param);
            }
        }

        if ("flag".equals(riskVO.getExt3())) {
            list = list.stream().collect(Collectors.collectingAndThen(
                    Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(RiriRisk::getRiskNo))
                    ), ArrayList::new));
        }
        return list;
    }


    @Override
    public List<RiriRisk> exportExcelRiriRisk(RiriRiskVO ririRisk, XtzyUser user) {
        //userCode    ext1:编号   ext2:宝钢股份
        List<RiriRisk> list = Lists.newArrayList();


        /*if (user != null){
            if("037199".equals(user.getUserCode()) || "admin".equals(user.getUserCode())) {
                ririRisk.setDeptCode(null);
            }else {
                ririRisk.setDeptCode(user.getExt1());
            }
        }*/
        RiriRiskVO riskVO = getRiskVo(ririRisk, user);
        servicePage();

        //判断张慧




//            Integer count = 0;
//            //user可能出现为空现象  这里还需修改
//            if (user != null){
//                count = xtzyRoleUserMapper.getCountByUserCodeAndRoleCode(user.getUserCode());
//            }
//
//            if (count != 0){
//                List<String> compIdList = riskVO.getCompIdList();
//                compIdList.add(user.getExt1());
//                riskVO.setCompIdList(compIdList);
//            }
//        }



        //list = ririRiskMapper.selectRiriRisk(riskVO);
        list = ririRiskMapper.exportExcelRiriRisk(riskVO);





        // 默认排序
        if (BeanUtils.sortList(list)) {
            for (RiriRisk risk : list) {
                RiriRisk param = new RiriRisk();
                param.setId(risk.getId());
                param.setRowOrder(risk.getRowOrder());
                ririRiskMapper.updateByPrimaryKeySelective(param);
            }
        }

        if ("flag".equals(riskVO.getExt3())) {
            list = list.stream().collect(Collectors.collectingAndThen(
                    Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(RiriRisk::getRiskNo))
                    ), ArrayList::new));
        }
        return list;
    }

    @Override
    public List<RiriRisk> selectNeedRiriRisk(RiriRiskVO ririRisk, XtzyUser user) {
        //userCode    ext1:编号   ext2:宝钢股份
        List<RiriRisk> list = Lists.newArrayList();

        RiriRiskVO riskVO = getRiskVo(ririRisk, user);
        servicePage();

        List<String> compIdList = riskVO.getCompIdList();
        compIdList.add(user.getExt1());
        riskVO.setCompIdList(compIdList);


        list = ririRiskMapper.selectRiriRisk(riskVO);





        // 默认排序
        if (BeanUtils.sortList(list)) {
            for (RiriRisk risk : list) {
                RiriRisk param = new RiriRisk();
                param.setId(risk.getId());
                param.setRowOrder(risk.getRowOrder());
                ririRiskMapper.updateByPrimaryKeySelective(param);
            }
        }

        if ("flag".equals(riskVO.getExt3())) {
            list = list.stream().collect(Collectors.collectingAndThen(
                    Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(RiriRisk::getRiskNo))
                    ), ArrayList::new));
        }
        return list;
    }

    public List<RiriRisk> queryRisk(RiriRiskVO ririRisk, XtzyUser user) {
        //userCode    ext1:编号   ext2:宝钢股份
        List<RiriRisk> list = Lists.newArrayList();

        //RiriRiskVO riskVO = getRiskVo(ririRisk, user);
        servicePage();

        /*List<String> compIdList = riskVO.getCompIdList();
        compIdList.add(user.getExt1());
        riskVO.setCompIdList(compIdList);*/


        list = ririRiskMapper.queryRisk(ririRisk);




        // 默认排序
        if (BeanUtils.sortList(list)) {
            for (RiriRisk risk : list) {
                RiriRisk param = new RiriRisk();
                param.setId(risk.getId());
                param.setRowOrder(risk.getRowOrder());
                ririRiskMapper.updateByPrimaryKeySelective(param);
            }
        }

        /*if ("flag".equals(riskVO.getExt3())) {
            list = list.stream().collect(Collectors.collectingAndThen(
                    Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(RiriRisk::getRiskNo))
                    ), ArrayList::new));
        }*/
        return list;
    }

    public RiriYyRisk queryYyById(String id){
        return ririRiskMapper.queryYyById(id);
    }

    public RiriImpRisk queryImpById(String id){
        return ririRiskMapper.queryImpById(id);
    }

    public List<RiriYyRisk> queryYyRisk(RiriYyRisk ririYyRisk, XtzyUser user) {
        //userCode    ext1:编号   ext2:宝钢股份
        /*if (StringUtils.isNotEmpty(ririYyRisk.getDeptCode())) {
            List<String> compList = new ArrayList<>();*/
            //找本公司及一下公司
            /*XtzyCompany company = companyMapper.selectByPrimaryKey(ririYyRisk.getDeptCode());
            if (Integer.valueOf(company.getPathLevel()) != 1) {
                //并非末级，找下级子公司
                if (1 != company.getEndLevelFlag()) {
                    List<XtzyCompany> companies = new ArrayList<>();
                    xtzyCompanyService.getNextCompany(company.getId(), companies);
                    companies.add(company);
                    compList.addAll(companies.stream().map(XtzyCompany::getId).collect(Collectors.toList()));
                }
            }
            ririYyRisk.setCompIdList(compList);
        } else {
            if (null != user) {
                ririYyRisk.setCompIdList(riaaRiskService.getCompCodes(user.getExt1(), ririYyRisk.getExt5()));
            }
        }*/
        servicePage();

        /*List<String> compIdList = ririYyRisk.getCompIdList();
        compIdList.add(user.getExt1());
        ririYyRisk.setCompIdList(compIdList);*/


        List<RiriYyRisk> list = ririRiskMapper.selectRiriYyRisk(ririYyRisk);


        // 默认排序
        if (BeanUtils.sortList(list)) {
            for (RiriYyRisk risk : list) {
                RiriYyRisk param = new RiriYyRisk();
                param.setId(risk.getId());
                param.setRowOrder(risk.getRowOrder());
                ririYyRiskMapper.updateByPrimaryKeySelective(param);
            }
        }

        return list;
    }

    public List<FltdProcess> queryProcessExt1(FltdProcess process){
        List<FltdProcess> fltdProcesses = ririRiskMapper.queryProcessExt1(process);
        return  fltdProcesses;
    }

    public List<RiriImpRisk> queryImpRisk(RiriImpRisk ririImpRisk, XtzyUser user) {
        //userCode    ext1:编号   ext2:宝钢股份
       /* if (StringUtils.isNotEmpty(ririImpRisk.getDeptCode())) {
            List<String> compList = new ArrayList<>();
            //找本公司及一下公司
            XtzyCompany company = companyMapper.selectByPrimaryKey(ririImpRisk.getDeptCode());
            if (Integer.valueOf(company.getPathLevel()) != 1) {
                //并非末级，找下级子公司
                if (1 != company.getEndLevelFlag()) {
                    List<XtzyCompany> companies = new ArrayList<>();
                    xtzyCompanyService.getNextCompany(company.getId(), companies);
                    companies.add(company);
                    compList.addAll(companies.stream().map(XtzyCompany::getId).collect(Collectors.toList()));
                }
            }
            ririImpRisk.setCompIdList(compList);
        } else {
            if (null != user) {
                ririImpRisk.setCompIdList(riaaRiskService.getCompCodes(user.getExt1(), ririImpRisk.getExt5()));
            }
        }*/
        servicePage();

        /*List<String> compIdList = ririImpRisk.getCompIdList();
        compIdList.add(user.getExt1());
        ririImpRisk.setCompIdList(compIdList);*/


        List<RiriImpRisk> list = ririRiskMapper.selectRiriImpRisk(ririImpRisk);


        // 默认排序
        if (BeanUtils.sortList(list)) {
            for (RiriImpRisk risk : list) {
                RiriImpRisk param = new RiriImpRisk();
                param.setId(risk.getId());
                param.setRowOrder(risk.getRowOrder());
                ririImpRiskMapper.updateByPrimaryKeySelective(param);
            }
        }

        return list;
    }
    @Override
    public List<RiriRisk> selectPredict(RiriRiskVO ririRisk, XtzyUser user) {
        //userCode    ext1:编号   ext2:宝钢股份
        List<RiriRisk> list = Lists.newArrayList();

        RiriRiskVO riskVO = getRiskVo(ririRisk, user);
        servicePage();

        List<String> compIdList = riskVO.getCompIdList();
        compIdList.add(user.getExt1());
        riskVO.setCompIdList(compIdList);


        list = ririRiskMapper.selectRiriRisk(riskVO);





        // 默认排序
        if (BeanUtils.sortList(list)) {
            for (RiriRisk risk : list) {
                RiriRisk param = new RiriRisk();
                param.setId(risk.getId());
                param.setRowOrder(risk.getRowOrder());
                ririRiskMapper.updateByPrimaryKeySelective(param);
            }
        }

        if ("flag".equals(riskVO.getExt3())) {
            list = list.stream().collect(Collectors.collectingAndThen(
                    Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(RiriRisk::getRiskNo))
                    ), ArrayList::new));
        }
        return list;
    }

    private RiriRiskVO getRiskVo(RiriRiskVO ririRisk, XtzyUser user) {
        RiriRiskVO riskVO = new RiriRiskVO();
        BeanUtils.copyBeanProp(riskVO, ririRisk);
        if (StringUtils.isNotEmpty(riskVO.getAcctYear())) {
            String acctYear = riskVO.getAcctYear().substring(0, 4);
            riskVO.setAcctYear(acctYear);
        }
        if (StringUtils.isNotEmpty(riskVO.getRiskType())) {
            if ((riskVO.getRiskType().length() > 2)) {
                riskVO.setDetailType(riskVO.getRiskType());
                riskVO.setRiskType(null);
            }
        }
        if (StringUtils.isNotEmpty(riskVO.getDeptCode())) {
            List<String> compList = new ArrayList<>();
            //找本公司及一下公司
            XtzyCompany company = companyMapper.selectByPrimaryKey(riskVO.getDeptCode());
            if (company!=null && Integer.valueOf(company.getPathLevel()) != 1) {
                //并非末级，找下级子公司
                if (1 != company.getEndLevelFlag()) {
                    List<XtzyCompany> companies = new ArrayList<>();
                    xtzyCompanyService.getNextCompany(company.getId(), companies);
                    companies.add(company);
                    compList.addAll(companies.stream().map(XtzyCompany::getId).collect(Collectors.toList()));
                }
            }
            riskVO.setCompIdList(compList);
        } else {
            if (null != user) {
                riskVO.setCompIdList(riaaRiskService.getCompCodes(user.getExt1(), riskVO.getExt5()));
            }
        }

        //riskVO.setManageCompCode(ShiroUtils.getUser().getManageCompCode());
        //ext4，导出标识用
//        if (StringUtils.isNotEmpty(riskVO.getExt4())) {
//            //年度和季度都为空的时候，默认导出当年度当季度的数据
////            if (StringUtils.isEmpty(riskVO.getAcctYear()) && StringUtils.isEmpty(riskVO.getQuarterCurrent())) {
////                riskVO.setAcctYear(DateUtils.format(new Date(), "yyyy"));
////                riskVO.setQuarterCurrent(DateUtils.getQuarter(new Date()));
////            }
//        }
        return riskVO;
    }

    @Override
    public Integer saveRisk(List<RiriRisk> ririRiskList) throws Exception {
        for (RiriRisk ririRisk : ririRiskList) {
            if (StringUtils.isEmpty(ririRisk.getRiskName())) {
                log.error("风险名称未填写，请填写!");
                throw new Exception("风险名称未填写，请填写!");
            }
            if (StringUtils.isEmpty(ririRisk.getRiskDesc())) {
                log.error("风险描述未填写，请填写!");
                throw new Exception("风险描述未填写，请填写!");
            }
            if (StringUtils.isEmpty(ririRisk.getDetailType())) {
                log.error("风险类别未填写，请填写!");
                throw new Exception("风险类别未填写，请填写!");
            }
            if (StringUtils.isEmpty(ririRisk.getDeptCode())) {
                ririRisk.setDeptCode(ShiroUtils.getUser().getExt1());
                ririRisk.setDeptName(ShiroUtils.getUser().getExt2());
            }
            log.info("保存风险库参数：" + ririRisk.toString());
            if (StringUtils.isEmpty(ririRisk.getAcctYear())) {
                ririRisk.setAcctYear(DateUtils.format(new Date(), "yyyy"));
            }
            if (StringUtils.isEmpty(ririRisk.getQuarterCurrent())) {
                ririRisk.setQuarterCurrent(DateUtils.getQuarter(new Date()));
            }
            ririRisk.setIsCurrentQuarter("Y");
            if (StringUtils.isEmpty(ririRisk.getId())) {
                //校验数据是否已经存在
                List<RiriRisk> list = ririRiskMapper.checkRiriRisk(ririRisk);
                if (CollectionUtils.isNotEmpty(list)) {
                    log.error(ririRisk.getDeptName() + "=该公司下已经存在风险名称为【" + ririRisk.getRiskName() + "】的数据！");
                    throw new Exception(ririRisk.getDeptName() + "=该公司下已经存在风险名称为【" + ririRisk.getRiskName() + "】的数据！");
                }
                //不存在就新增
                ririRisk = (RiriRisk) BeanUtils.initBean(ririRisk);
                ririRisk.setExt4(ririRisk.getCompCode());
                ririRisk.setExt5(ririRisk.getCompName());
                insertRisk(ririRisk);
            } else {
                ririRisk = (RiriRisk) BeanUtils.updateBean(ririRisk);
                updateRisk(ririRisk);
            }
        }
        return 1;
    }

    public Integer saveYyRisk(List<RiriYyRisk> ririYyRiskList) throws Exception {
        for (RiriYyRisk ririYyRisk : ririYyRiskList) {

            if (StringUtils.isEmpty(ririYyRisk.getStatus())) {
                ririYyRisk.setStatus("A01");
                ririYyRisk.setStatusName("待填报");
            }
            if (StringUtils.isEmpty(ririYyRisk.getDeptCode())) {
                ririYyRisk.setDeptCode(ShiroUtils.getUser().getExt1());
                ririYyRisk.setDeptName(ShiroUtils.getUser().getExt2());
            }
            if (StringUtils.isEmpty(ririYyRisk.getAcctYear())) {
                ririYyRisk.setAcctYear(DateUtils.format(new Date(), "yyyy"));
            }
            if (StringUtils.isEmpty(ririYyRisk.getQuarterCurrent())) {
                ririYyRisk.setQuarterCurrent(DateUtils.getQuarter(new Date()));
            }
            if (StringUtils.isEmpty(ririYyRisk.getDeleteFlag())){
                ririYyRisk.setDeleteFlag("0");
            }
            // 管理员标记没写
            log.info("保存经营投资纪律风险参数：" + ririYyRisk.toString());
            if (StringUtils.isEmpty(ririYyRisk.getId())) {
                //校验数据是否已经存在
                List<RiriYyRisk> list = ririRiskMapper.checkRiriYyRisk(ririYyRisk);
                if (CollectionUtils.isNotEmpty(list)) {
                    log.error(ririYyRisk.getDeptName() + "=该公司下已经存在措施为【" + ririYyRisk.getRePlan() + "】的数据！");
                    throw new Exception(ririYyRisk.getRePlan() + "=该公司下已经存在措施为【" + ririYyRisk.getRePlan() + "】的数据！");
                }
                //不存在就新增
                ririYyRisk = (RiriYyRisk) BeanUtils.initBean(ririYyRisk);
                ririRiskMapper.insertRiRiYyRisk(ririYyRisk);
            } else {
                //保留原主键ID
                String id=ririYyRisk.getId();
                ririYyRisk = (RiriYyRisk) BeanUtils.initBean(ririYyRisk);
                ririYyRisk.setId(id);
                ririRiskMapper.updateByRiskId(ririYyRisk);
            }
        }
        return 1;
    }



    public Integer saveImpRisk(List<RiriImpRisk> ririImpRiskList) throws Exception {
        for (RiriImpRisk ririImpRisk : ririImpRiskList) {

            if (StringUtils.isEmpty(ririImpRisk.getStatus())) {
                ririImpRisk.setStatus("A01");
                ririImpRisk.setStatusName("待填报");
            }
            if (StringUtils.isEmpty(ririImpRisk.getDeleteFlag())){
                ririImpRisk.setDeleteFlag("0");
            }
            if (StringUtils.isEmpty(ririImpRisk.getDeptCode())) {
                ririImpRisk.setDeptCode(ShiroUtils.getUser().getExt1());
                ririImpRisk.setDeptName(ShiroUtils.getUser().getExt2());
            }
            if (StringUtils.isEmpty(ririImpRisk.getAcctYear())) {
                ririImpRisk.setAcctYear(DateUtils.format(new Date(), "yyyy"));
            }
            if (StringUtils.isEmpty(ririImpRisk.getQuarterCurrent())) {
                ririImpRisk.setQuarterCurrent(DateUtils.getQuarter(new Date()));
            }
            log.info("保存经营风险事件跟踪参数：" + ririImpRisk.toString());
            if (StringUtils.isEmpty(ririImpRisk.getId())) {
                //校验数据是否已经存在
                /*List<RiriYyRisk> list = ririRiskMapper.checkRiriYyRisk(ririYyRisk);
                if (CollectionUtils.isNotEmpty(list)) {
                    log.error(ririYyRisk.getDeptName() + "=该公司下已经存在措施为【" + ririYyRisk.getRePlan() + "】的数据！");
                    throw new Exception(ririYyRisk.getRePlan() + "=该公司下已经存在措施为【" + ririYyRisk.getRePlan() + "】的数据！");
                }*/
                //不存在就新增
                ririImpRisk = (RiriImpRisk) BeanUtils.initBean(ririImpRisk);
                ririRiskMapper.insertRiRiImpRisk(ririImpRisk);
            } else {
                ririRiskMapper.updateByImpRiskId(ririImpRisk);
            }
        }
        return 1;
    }
    public Integer saveProcessExt1(FltdProcess process){
        ririRiskMapper.saveProcessExt1(process);

        return 1;
    }




    @Override
    public Integer importSaveRisk(List<RiriRisk> ririRiskList) throws Exception {
        for (RiriRisk ririRisk : ririRiskList) {
            if (StringUtils.isEmpty(ririRisk.getRiskName())) {
                log.error("风险名称未填写，请填写!");
                throw new Exception("风险名称未填写，请填写!");
            }
            if (StringUtils.isEmpty(ririRisk.getRiskDesc())) {
                log.error("风险描述未填写，请填写!");
                throw new Exception("风险描述未填写，请填写!");
            }
            if (StringUtils.isEmpty(ririRisk.getDetailType())) {
                log.error("风险类别未填写，请填写!");
                throw new Exception("风险类别未填写，请填写!");
            }
            if (StringUtils.isEmpty(ririRisk.getDeptCode())) {
                ririRisk.setDeptCode(ShiroUtils.getUser().getExt1());
                ririRisk.setDeptName(ShiroUtils.getUser().getExt2());
            }
            log.info("保存风险库参数：" + ririRisk.toString());
            if (StringUtils.isEmpty(ririRisk.getAcctYear())) {
                ririRisk.setAcctYear(DateUtils.format(new Date(), "yyyy"));
            }
            if (StringUtils.isEmpty(ririRisk.getQuarterCurrent())) {
                ririRisk.setQuarterCurrent(DateUtils.getQuarter(new Date()));
            }
            ririRisk.setIsCurrentQuarter("N");
            if (StringUtils.isEmpty(ririRisk.getId())) {
                //校验数据是否已经存在
                List<RiriRisk> list = ririRiskMapper.checkRiriRisk(ririRisk);
                if (CollectionUtils.isNotEmpty(list)) {
                    log.error(ririRisk.getDeptName() + "=该公司下已经存在风险名称为【" + ririRisk.getRiskName() + "】的数据！");
                    throw new Exception(ririRisk.getDeptName() + "=该公司下已经存在风险名称为【" + ririRisk.getRiskName() + "】的数据！");
                }
                //不存在就新增
                ririRisk = (RiriRisk) BeanUtils.initBean(ririRisk);
                ririRisk.setExt4(ririRisk.getCompCode());
                ririRisk.setExt5(ririRisk.getCompName());
                insertRisk(ririRisk);
            } else {
                updateRisk(ririRisk);
            }
        }
        return 1;
    }

    @Override
    public Integer importRisk(List<RiriRisk> ririRiskList) throws Exception {
        for (RiriRisk ririRisk : ririRiskList) {
            ririRisk = (RiriRisk) BeanUtils.initBean(ririRisk);
            ririRisk.setIsCurrentQuarter("N");
            ririRiskMapper.insert(ririRisk);
        }
        return 1;
    }


    @Override
    public Integer submitRiriRisk(List<RiriRisk> ririRisk) {
        for (RiriRisk risk : ririRisk) {
            risk.setStatus("A03");
            risk.setStatusName("领导审核");
            int i = ririRiskMapper.updateByPrimaryKeySelective(risk);
            System.out.println(i);
        }
        return 1;
    }

    @Override
    public Integer getLastQuarter() {
        //获取当前年份
        String year = DateUtils.format(new Date(), "yyyy");
        //获取当前季度
        String quarter = DateUtils.getQuarter(new Date());
        //如果当前季度是1，找上一年四季度的数据
        if ("1".equals(quarter)) {

            Integer yyyy = Integer.valueOf(year) - 1;
            year = yyyy.toString();
            quarter = "4";
        } else {
            //季度大于1，找当年上一季度的数据
            Integer jidu = Integer.valueOf(quarter) - 1;
            quarter = jidu.toString();
        }

        RiriRiskVO ririRisk = new RiriRiskVO();
        ririRisk.setAcctYear(year);
        ririRisk.setQuarterCurrent(quarter);
        List<RiriRisk> riskList = ririRiskMapper.selectRiriRisk(ririRisk);
        if (CollectionUtils.isEmpty(riskList)) {
            return null;
        }
        for (RiriRisk risk : riskList) {
            //如果风险自评的历史ID为空，默认填自己，如果不为空，则不处理
            if (StringUtils.isEmpty(risk.getHisRiskId())) {
                risk.setHisRiskId(risk.getId());
                ririRiskMapper.updateByPrimaryKey(risk);
            }
            risk.setQuarterCurrent(DateUtils.getQuarter(new Date()));
            risk.setStatus("A01");
            risk.setStatusName("待填报");
            risk.setAdminFlag("N");
            risk = (RiriRisk) BeanUtils.initBean(risk);
            ririRiskMapper.insert(risk);
        }
        return 1;
    }

    public Integer insertRisk(RiriRisk ririRisk) {
        XtzyCompany company = companyMapper.getCompanyInfo(ririRisk.getDeptCode());
        //如果是公司，公司和部门是一样的，如果不是公司，找到上级公司
        if ("1".equals(company.getCompType())) {
            ririRisk.setCompCode(ririRisk.getDeptCode());
            ririRisk.setCompName(ririRisk.getDeptName());
        } else {
            company = companyMapper.getCompByCompCode(company.getPathCode());
            ririRisk.setCompCode(company.getCompCode());
            ririRisk.setCompName(company.getCompName());
        }
        if (StringUtils.isEmpty(ririRisk.getManageCompCode())) {
            XtzyCompany company1 = companyMapper.getCompanyInfo(ShiroUtils.getUser().getExt1());
            XtzyCompany company2 = companyMapper.getCompByCompCode(company1.getPathCode());
            ririRisk.setManageCompCode(company2.getCompCode());
            ririRisk.setManageCompName(company2.getCompName());
        }
        //风险库的编码根据公司和大分类流水
        String groupFlag = "ririRisk_" + ririRisk.getAcctYear() + "_" + company.getCompCode() + "_" + ririRisk.getRiskType();
        //获得流水号
        String code = sequencesService.generateCodeById(groupFlag, "ririRisk.riskNo", company.getCompCode(), ririRisk.getRiskType(), ririRisk.getDetailType());
        ririRisk.setRiskNo(code);
        ririRisk.setHisRiskId(ririRisk.getId());
        Integer rowOrder;
        Integer maxRowOrder = ririRiskMapper.queryMax(ririRisk.getAcctYear());
        if (maxRowOrder == null) {
            rowOrder = 1;
        } else {
            rowOrder = Integer.valueOf(maxRowOrder) + 1;
        }
        ririRisk.setRowOrder(rowOrder);
        //计算风险等级
        if (StringUtils.isNotEmpty(ririRisk.getImpactDegree()) && StringUtils.isNotEmpty(ririRisk.getRiskProbability())) {
            Map<String, String> map = getRiskLevel(ririRisk.getRiskProbability(), ririRisk.getImpactDegree());
            ririRisk.setAssessScore(Short.valueOf(map.get("assessScore")));
            ririRisk.setRiskLevel(map.get("riskLevel"));
            ririRisk.setRiskLevelName(map.get("riskLevelName"));
        }
        return ririRiskMapper.insert(ririRisk);
    }

    /**
     * 计算得出风险等级，风险评分
     *
     * @param riskProbability
     * @param impactDegree
     * @return
     */
    public Map<String, String> getRiskLevel(String riskProbability, String impactDegree) {
        Map<String, String> resultMap = Maps.newHashMap();
        Integer riskNum = Integer.valueOf(impactDegree) * Integer.valueOf(riskProbability);
        resultMap.put("assessScore", riskNum.toString());
        List<XtaaCode> codeList = xtaaCodeService.selectDataByDDTypeCode("RISK_LEVEL");
        for (XtaaCode code : codeList) {
            Integer ext1 = Integer.valueOf(code.getExt1());
            Integer ext2 = Integer.valueOf(code.getExt2());
            if (riskNum >= ext1 && riskNum <= ext2) {
                resultMap.put("riskLevel", code.getDdCode());
                resultMap.put("riskLevelName", code.getDdName());
            }
        }
        return resultMap;
    }

    @Override
    public Integer updateRisk(RiriRisk ririRisk) {
        if(StringUtils.isNotEmpty(ririRisk.getDeptCode())) {
            XtzyCompany company = companyMapper.getCompanyInfo(ririRisk.getDeptCode());
            //如果是公司，公司和部门是一样的，如果不是公司，找到上级公司
            if ("1".equals(company.getCompType())) {
                ririRisk.setCompCode(ririRisk.getCompCode());
                ririRisk.setCompName(ririRisk.getCompName());
            } else {
                //获取一级子公司或部门
                company = companyMapper.getCompByCompCode(company.getPathCode());
                ririRisk.setCompCode(company.getCompCode());
                ririRisk.setCompName(company.getCompName());
            }
        }
        //计算风险等级
        if (StringUtils.isNotEmpty(ririRisk.getImpactDegree()) && StringUtils.isNotEmpty(ririRisk.getRiskProbability())) {
            Map<String, String> map = getRiskLevel(ririRisk.getRiskProbability(), ririRisk.getImpactDegree());
            ririRisk.setAssessScore(Short.valueOf(map.get("assessScore")));
            ririRisk.setRiskLevel(map.get("riskLevel"));
            ririRisk.setRiskLevelName(map.get("riskLevelName"));
        }
        return ririRiskMapper.updateByPrimaryKeySelective(ririRisk);
    }

    @Override
    public Integer addHistory(List<String> ids) {
        for (String id : ids) {
            RiriRisk risk = ririRiskMapper.selectByPrimaryKey(id);
            RiriRiskHis riskHis = new RiriRiskHis();
            BeanUtils.copyBeanProp(riskHis, risk);
            riskHis = (RiriRiskHis) BeanUtils.initBean(riskHis);
            riskHis.setRiskId(risk.getId());
            riskHis.setQuarterCode(risk.getQuarterCurrent());
            ririRiskHisMapper.insert(riskHis);
        }
        return 1;
    }


    @Override
    public List<RiriRisk> getRiriRiskByIds(List<String> ids) {
        return ririRiskMapper.getRiriRiskByIds(ids);
    }

    @Override
    public Integer deleteById(List<String> ids, String status, String statusName) throws Exception {
        for (String id : ids) {
            RiriRisk ririRisk = ririRiskMapper.selectByPrimaryKey(id);
            List<RiimRiskImport> riskImportList = riskImportMapper.queryByRiskNo(ririRisk.getRiskNo(), ririRisk.getAcctYear());
            if (CollectionUtils.isEmpty(riskImportList)) {
                deleteData(id, status, statusName, ririRisk.getHisRiskId());
            } else {
                Boolean check = false;
                for (RiimRiskImport riskImport : riskImportList) {
                    if ("09".equals(riskImport.getStatus())) {
                        check = true;
                        break;
                    }
                }
                if (check) {
                    ririRiskMapper.deleteById(id, status, statusName);
                } else {
                    throw new Exception("存在未关闭的重点风险数据，不允许删除！");
                }
            }

        }
        return 1;
    }

    public Integer deleteYyById(List<String> ids, String deleteFlag, Date deleteTime,String deleteBy) throws Exception{
        for(String id : ids) {
            ririRiskMapper.deleteYyById(id, deleteFlag, deleteTime,deleteBy);
        }
        return 1;
    }

    public Integer deleteImpById(List<String> ids, String deleteFlag, Date deleteTime,String deleteBy) throws Exception{
        for(String id : ids) {
            ririRiskMapper.deleteImpById(id, deleteFlag, deleteTime,deleteBy);
        }
        return 1;
    }

    private void deleteData(String id, String status, String statusName, String hisRiskId) {
        if (StringUtils.isNotEmpty(hisRiskId)) {
            //不为空，逻辑删除
            Integer number = ririRiskMapper.selectCountHisId(hisRiskId);
            if (number > 1) {
                ririRiskMapper.deleteById(id, status, statusName);
            } else {
                ririRiskMapper.deleteByPrimaryKey(id);
            }
        } else {
            //为空，草稿状态时物理删除
            ririRiskMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public List<RiriRisk> selectTopThree(RiskTopThreeVO riskTopThree) {
        List<RiriRisk> riskList = Lists.newArrayList();
        XtzyCompany company = new XtzyCompany();
        company.setDepartmentClass(riskTopThree.getDepartmentClass());
        company.setRiskFlag("Y");
        List<XtzyCompany> companyList = xtzyCompanyService.queryCompany(company);
        if (StringUtils.isNotEmpty(riskTopThree.getRiskType())) {
            if ((riskTopThree.getRiskType().length() > 2)) {
                riskTopThree.setDetailType(riskTopThree.getRiskType());
                riskTopThree.setRiskType(null);
            }
        }
        if (StringUtils.isNotEmpty(riskTopThree.getAcctYear())) {
            String year = riskTopThree.getAcctYear().substring(0, 4);
            riskTopThree.setAcctYear(year);
        }
        if (StringUtils.isEmpty(riskTopThree.getAcctYear()) && StringUtils.isEmpty(riskTopThree.getQuarterCurrent())) {
            riskTopThree.setAcctYear(DateUtils.format(new Date(),"yyyy"));
            selectNextRiskList(riskTopThree, companyList, riskList, DateUtils.getQuarter(new Date()));
        } else {
            riskList = selectRiskList(riskTopThree, companyList);
        }
        return riskList;
    }

    private List<RiriRisk> selectRiskList(RiskTopThreeVO riskTopThree, List<XtzyCompany> companyList) {
        List<RiriRisk> list = Lists.newArrayList();
        for (XtzyCompany company : companyList) {
            riskTopThree.setDeptCode(company.getCompCode());
            riskTopThree.setStatus("A03");
            List<RiriRisk> riskList = getTopThree(riskTopThree);
            list.addAll(riskList);
        }
        if (CollectionUtils.isEmpty(list)) {
            queryRisks(riskTopThree, companyList);
        }
        return list;
    }

    private List<RiriRisk> queryRisks(RiskTopThreeVO riskTopThree, List<XtzyCompany> companyList) {
        List<RiriRisk> list = Lists.newArrayList();
        for (XtzyCompany company : companyList) {
            riskTopThree.setDeptCode(company.getCompCode());
            riskTopThree.setStatus("A03");
            List<RiriRisk> riskList = getTopThree(riskTopThree);
            list.addAll(riskList);
        }
        return list;
    }

    /**
     * 默认年度季度为空的查询，向上一个季度查询直到查询到数据！
     *
     * @param riskTopThree
     * @param companyList
     * @return
     */
    private void selectNextRiskList(RiskTopThreeVO riskTopThree, List<XtzyCompany> companyList, List<RiriRisk> riskList, String quarter) {
        if (CollectionUtils.isNotEmpty(riskList)) {
            return;
        }
        //截止年度季度
        String stopYear = String.valueOf(Integer.valueOf(DateUtils.format(new Date(), "yyyy")) - 2);
        String stopQuarter = "4";
        //上一季度
        if (stopYear.equals(riskTopThree.getAcctYear()) && stopQuarter.equals(quarter)) {
            return;
        }
        for (XtzyCompany company : companyList) {
            riskTopThree.setDeptCode(company.getCompCode());
            riskTopThree.setQuarterCurrent(quarter);
            riskTopThree.setStatus("A03");
            List<RiriRisk> ririRisks = getTopThree(riskTopThree);
            riskList.addAll(ririRisks);

        }
        if ("1".equals(quarter)) {
            riskTopThree.setAcctYear(String.valueOf(Integer.valueOf(riskTopThree.getAcctYear()) - 1));
            quarter="4";
        }else{
            quarter=String.valueOf(Integer.valueOf(quarter)-1);
        }
        selectNextRiskList(riskTopThree, companyList, riskList, quarter);
    }

    /**
     * 获取年度和上一个季度
     *
     * @param year
     * @param quarterCode
     * @return
     */
    private Map<String, String> resultMap(String year, String quarterCode) {
        Map<String, String> map = Maps.newHashMap();
        String acctYear = "";
        String quarterCurrent = "";
        if (StringUtils.isNotEmpty(year) && StringUtils.isNotEmpty(quarterCode)) {
            if (1 == Integer.valueOf(quarterCode)) {
                acctYear = String.valueOf(Integer.valueOf(year) - 1);
                quarterCurrent = "4";
            } else {
                acctYear = year;
                quarterCurrent = String.valueOf(Integer.valueOf(quarterCode) - 1);
            }
        }
        map.put("acctYear", acctYear);
        map.put("quarterCurrent", quarterCurrent);
        return map;
    }

    @Override
    public void saveTimingTask(Map mapParam,List<XtzyCompany> companyList,String jobId) throws Exception {
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;
        int startNum = 0;
        try {
            FltdTaskVO taskVO = new FltdTaskVO();
            if("BGTA".equals(mapParam.get("manageCompCode").toString())){
                taskVO.setFlowNo("fengxianziping");
                taskVO.setFlowName("风险自评");
            }else{
                taskVO.setFlowNo("jidiziping");
                taskVO.setFlowName("基地风险自评审核");
            }
            taskVO.setAcctYear(mapParam.get("acctYear").toString());
            taskVO.setQuarterCode(mapParam.get("quarterCurrent").toString());
            taskVO.setQuarterName(DateUtils.getQuarterName(taskVO.getQuarterCode()));
            taskVO.setManageCompCode(mapParam.get("manageCompCode").toString());
            taskVO.setManageCompName(mapParam.get("manageCompName").toString());
            for (XtzyCompany company : companyList) {
                taskVO.setBizGuid(taskVO.getAcctYear() + "_" + taskVO.getQuarterCode() + "_" + company.getCompCode());
                taskVO.setCustomCompany(company);
                taskVO.setCompCode(company.getCompCode());
                taskVO.setCompName(company.getCompName());
                taskVO.setDeptCode(company.getCompCode());
                taskVO.setDeptName(company.getCompName());
                String bizDesc = taskVO.getAcctYear() + "年度-" + taskVO.getQuarterName() + "-" + taskVO.getCustomCompany().getCompName() + "-风险自评";
                taskVO.setBizName(bizDesc);
                taskVO.setBizDesc(bizDesc);
                taskVO.setGroupCondition(taskVO.getAcctYear() + taskVO.getQuarterCode());

                //判断风险自评是否已经下发，当年当季度只能下发一次不可以重复下发；
                FltdTask task = new FltdTask();
                task.setFlowNo(taskVO.getFlowNo());
                task.setAcctYear(taskVO.getAcctYear());
                task.setQuarterCode(taskVO.getQuarterCode());
                task.setDeptCode(company.getCompCode());
                FltdTask fltdTask = fltdTaskService.selectExistTask(task);
                if (fltdTask == null) {
                    try {
                        startNum++;
                        //把上季度的数据放到这个季度来
                        getLastRiskData(mapParam, company.getCompCode());
                        //启动流程
                        fltdProcessService.doStart(taskVO);
                        logs.add(fltdProcessService.getLog("风险自评-流程启动成功", 0, "自评单位：" + company.getCompName(), jobId));
                    } catch (Exception e) {
                        logs.add(fltdProcessService.getLog("风险自评-流程启动失败", 1, e.getMessage(), jobId));
                        error = e;
                        break;
                    }
                }
            }
            if (startNum == 0) {
                logs.add(fltdProcessService.getLog("风险自评-流程启动成功", 1, "未查到可以下发的风险自评数据", jobId));
            }
        } catch (Exception e) {
            logs.add(fltdProcessService.getLog("风险自评-下发异常", 1, e.getMessage(), jobId));
            error = e;
        }
        // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }
    }

    @Override
    public void updateRowOrder(RiriRiskVO ririRisk, XtzyUser user) {
        RiriRiskVO riskVO = getRiskVo(ririRisk, user);
        List<RiriRisk> riskList = ririRiskMapper.selectRiriRisk(riskVO);
        RiriRisk risk = get(ririRisk.getId());
        int i = riskList.indexOf(risk);
        if ("up".equals(ririRisk.getExt2())) {
            i--;
        } else {
            i++;
        }
        if (i < riskList.size() && i >= 0) {
            RiriRisk riskNext = riskList.get(i);
            Integer rowOrder1 = risk.getRowOrder();
            Integer rowOrder2 = riskNext.getRowOrder();
            risk.setRowOrder(rowOrder2);
            update(risk);
            riskNext.setRowOrder(rowOrder1);
            update(riskNext);
        }

    }

    @Override
    public List<RiriRisk> getTopThree(RiriRisk ririRisk) {
        RiskTopThreeVO riskTopThreeVO = new RiskTopThreeVO();
        BeanUtils.copyBeanProp(riskTopThreeVO,ririRisk);
        String compCode=compCodeTemp;
        //riskTopThreeVO.setCompCode(compCodeTemp);
       // riskTopThreeVO.setStatus(ststusTemp);
        if (StringUtils.isNotEmpty(riskTopThreeVO.getCompCode())) {
            List<String> compList = new ArrayList<>();
            //找本公司及一下公司

            XtzyCompany company = companyMapper.selectByPrimaryKey(riskTopThreeVO.getCompCode());
            if (Integer.valueOf(company.getPathLevel()) != 1) {
                //并非末级，找下级子公司
                if (1 != company.getEndLevelFlag()) {
                    List<XtzyCompany> companies = new ArrayList<>();
                    xtzyCompanyService.getNextCompany(company.getId(), companies);
                    companies.add(company);
                    compList.addAll(companies.stream().map(XtzyCompany::getId).collect(Collectors.toList()));
                }
            }
            riskTopThreeVO.setCompIdList(compList);
        } else {
            List<String> compList = new ArrayList<>();
            compList.add(riskTopThreeVO.getDeptCode());
            riskTopThreeVO.setCompIdList(compList);
        }
        return ririRiskMapper.selectTopThree(riskTopThreeVO);
    }

    @Override
    public List<RiriRisk> queryImportantRiskData(RiriRiskVO ririRisk) {
        RiskTopThreeVO riskTopThreeVO = new RiskTopThreeVO();
        BeanUtils.copyBeanProp(riskTopThreeVO,ririRisk);
        servicePage();
        List<RiriRisk> riskList =ririRiskMapper.queryImportantRiskData(riskTopThreeVO);
        return riskList;
    }

    /**
     * 获取上一季度得自评数据
     *
     * @param map
     */
    private void getLastRiskData(Map<String, String> map, String deptCode) {
        String manageCompCode = map.get("manageCompCode");
        // 获取年度和季度
        Map<String, String> returnMap = resultMap(map.get("acctYear"), map.get("quarterCurrent"));
        String acctYear = returnMap.get("acctYear");
        String quarterCurrent = returnMap.get("quarterCurrent");

        RiriRiskVO ririRisk = new RiriRiskVO();
        ririRisk.setAcctYear(map.get("acctYear"));
        ririRisk.setQuarterCurrent(map.get("quarterCurrent"));
        ririRisk.setManageCompCode(manageCompCode);
//        ririRisk.setDeptCode(deptCode);
        if (StringUtils.isNotEmpty(deptCode)) {
            ririRisk.setCompIdList(Arrays.asList(deptCode));
        }
        List<RiriRisk> currentRiskList = ririRiskMapper.selectRiriRisk(ririRisk);

        ririRisk.setAcctYear(acctYear);
        ririRisk.setQuarterCurrent(quarterCurrent);
        List<RiriRisk> riskList = ririRiskMapper.selectRiriRisk(ririRisk);
        if (CollectionUtils.isEmpty(riskList)) {
            return;
        }

        // 如果是手工新增的自评状态要改为待填报
        for (RiriRisk currentRisk : currentRiskList) {
            if ("A03".equals(currentRisk.getStatus())) {
                RiriRisk param = new RiriRisk();
                param.setId(currentRisk.getId());
                param.setStatus("A01");
                param.setStatusName("待填报");
                ririRiskMapper.updateByPrimaryKeySelective(param);
            }
        }

        out: for (RiriRisk risk : riskList) {
            // 需排除当季度已经录入的自评
            for (RiriRisk currentRisk : currentRiskList) {
                if (risk.getRiskNo().equals(currentRisk.getRiskNo())) {
                    RiriRisk param = new RiriRisk();
                    param.setId(currentRisk.getId());
                    param.setStatus("A01");
                    param.setStatusName("待填报");
                    ririRiskMapper.updateByPrimaryKeySelective(param);
                    continue out;
                }
            }
            //如果风险自评的历史ID为空，默认填自己，如果不为空，则不处理
            if (StringUtils.isEmpty(risk.getHisRiskId())) {
                risk.setHisRiskId(risk.getId());
                ririRiskMapper.updateByPrimaryKey(risk);
            }
            Integer rowOrder = 1;
            Integer maxRowOrder = ririRiskMapper.queryMax(map.get("acctYear"));
            if (maxRowOrder == null) {
                rowOrder = 1;
            } else {
                rowOrder = maxRowOrder + 1;
            }
            risk.setRowOrder(rowOrder);
            risk.setAcctYear(map.get("acctYear"));
            risk.setQuarterCurrent(map.get("quarterCurrent"));
            risk.setStatus("A01");
            risk.setStatusName("待填报");
            risk.setAdminFlag("N");
            risk.setTopThreeFlag("N");
            risk = (RiriRisk) BeanUtils.initBean(risk);
            ririRiskMapper.insert(risk);
        }
    }

    @Override
    public boolean updateStatus(Map<String, Object> params) {
        RiriRiskVO riskVO = new RiriRiskVO();
        riskVO.setAcctYear(params.get("acctYear").toString());
        riskVO.setQuarterCurrent(params.get("quarterCurrent").toString());
        riskVO.setDeptCode(params.get("deptCode").toString());
        riskVO.setStatus(params.get("status").toString());
        String statusName = params.get("nextStatusName").toString();
        String status = params.get("nextStatus").toString();
        RiriYyRisk ririYyRisk = new RiriYyRisk();
        ririYyRisk.setAcctYear(params.get("acctYear").toString());
        ririYyRisk.setQuarterCurrent(params.get("quarterCurrent").toString());
        ririYyRisk.setDeptCode(params.get("deptCode").toString());
        ririYyRisk.setStatus(params.get("status").toString());
        ririYyRisk.setStatusName(statusName);
        RiriImpRisk ririImpRisk = new RiriImpRisk();
        ririImpRisk.setAcctYear(params.get("acctYear").toString());
        ririImpRisk.setQuarterCurrent(params.get("quarterCurrent").toString());
        ririImpRisk.setDeptCode(params.get("deptCode").toString());
        ririImpRisk.setStatus(params.get("status").toString());
        ririImpRisk.setStatusName(statusName);
        List<RiriImpRisk> ririImpRisks = queryImpRisk(ririImpRisk,getUser());
        List<RiriYyRisk> ririYyRisks = queryYyRisk(ririYyRisk,getUser());
        List<RiriRisk> riskList = selectRiriRisk(riskVO, null);
        if (StringUtils.isNotEmpty(ririYyRisks)){
            List<String> yyIds = ririYyRisks.stream().map(RiriYyRisk::getId).collect(Collectors.toList());
            ririRiskMapper.updateYyStatus(yyIds, status, statusName);
        }
        if (StringUtils.isNotEmpty(ririImpRisks)){
            List<String> impIds = ririImpRisks.stream().map(RiriImpRisk::getId).collect(Collectors.toList());
            ririRiskMapper.updateImpStatus(impIds, status, statusName);
        }
        if (StringUtils.isNotEmpty(riskList)) {
            List<String> ids = riskList.stream().map(RiriRisk::getId).collect(Collectors.toList());
            if ("A03".equals(params.get("status"))) {
                ririRiskMapper.updateAuditDate(ids,new Date());
            }
            if (ririRiskMapper.updateStatus(ids, status, statusName) > 0) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }


    @Override
    public void doCarryForward(String acctYear, String quarterCurrent) throws Exception {
        //判断风险自评是否已经下发，当年当季度只能下发一次不可以重复下发；
        FltdTask task = new FltdTask();
        task.setFlowNo("fengxianziping");
        task.setAcctYear(acctYear);
        task.setQuarterCode(quarterCurrent);
        FltdTask fltdTask = fltdTaskService.selectExistTask(task);
        if (fltdTask == null) {
            Map<String, String> map = new HashMap<>();
            map.put("acctYear", acctYear);
            map.put("quarterCurrent", quarterCurrent);
            getLastRiskData(map, "");
        } else {
            throw new Exception("本季度已经下发过风险自评，无法结转！");
        }
    }

    private static String compCodeTemp= "";
    private static String ststusTemp= "";
    @Override
    public List<RiRiRiskDetailVO> selectRiRiRiskDetails(RiRiRiskDetailParamVO vo){
        String flowNoParam=vo.getFlowNo();
        String userCode=ShiroUtils.getUser().getUserCode();
        String compCode="";
        //compCodeTemp=vo.getManageCompCode();
        //ststusTemp=vo.getNodeCode();
        List<XtzyUserVO> userRole=xtzyRoleUserMapper.selectRoleByUserCode(userCode);
        if (userRole.stream().anyMatch(m->m.getRoleKey().equals("RISK03")) ||
                userRole.stream().anyMatch(m->m.getRoleKey().equals("COMP03"))) {
            compCode=ShiroUtils.getUser().getManageCompCode();
        }

        if("BGTA".equals(vo.getManageCompCode())){
            flowNoParam="fengxianziping";
        }else{
            flowNoParam="jidiziping";
        }
        vo.setFlowNo(flowNoParam);
        vo.setCompCode(compCode);
        servicePage();
        List<RiRiRiskDetailVO> list= ririRiskMapper.selectRiRiRiskDetails(vo);
        return list;
    }

    @Override
    public Integer updateTop3(RiriRisk ririRisk) throws Exception {
        if ("Y".equals(ririRisk.getTopThreeFlag())) {
            //List<RiriRisk> topThree = getTopThree(ririRisk);
            List<RiriRisk> topThree = getThisTaskTopThree(ririRisk);
            if (topThree.size() >= 3) {
                throw new Exception("本期top3自评已经有3条！");
            }
        }

        RiriRisk param = new RiriRisk();
        param.setId(ririRisk.getId());
        param.setTopThreeFlag(ririRisk.getTopThreeFlag());
        return ririRiskMapper.updateByPrimaryKeySelective(param);
    }

    private List<RiriRisk> getThisTaskTopThree(RiriRisk ririRisk) {
        RiriRiskVO ririRiskVO = new RiriRiskVO();
        ririRiskVO.setQuarterCurrent(ririRisk.getQuarterCurrent());
        ririRiskVO.setAcctYear(ririRisk.getAcctYear());
        ririRiskVO.setTopThreeFlag("Y");
        ririRiskVO.setDeptCode(ririRisk.getDeptCode());
        List<RiriRisk> ririRisks = selectNeedRiriRisk(ririRiskVO, getUser());
        return ririRisks;
    }
    @Override
    public List<RiriRisk> queryRiriRiskData(RiriRiskVO ririRiskVO) {
        List<RiriRisk> ririRiskData = ririRiskMapper.queryRiriRiskData(ririRiskVO);
        return ririRiskData;
    }

    @Override
    public Integer importantRiskUpdate(RiriRisk ririRisk) {
        RiriRisk param = new RiriRisk();
        param.setId(ririRisk.getId());
        param.setTopThreeFlag(ririRisk.getTopThreeFlag());
        return ririRiskMapper.updateByPrimaryKeySelective(param);
    }

    @Override
    public boolean doBefore(Map<String, Object> params) {
        String acctYear = (String) params.get("acctYear");
        String quarterCode = (String) params.get("quarterCode");
        String deptCode = (String) params.get("deptCode");
        String manageCompCode = (String) params.get("manageCompCode");
        String bizGuid = (String) params.get("bizGuid");
        RiriYyRisk ririYyRisk = new RiriYyRisk();
        ririYyRisk.setAcctYear(acctYear);
        ririYyRisk.setQuarterCurrent(quarterCode);
        ririYyRisk.setDeptCode(deptCode);
        ririYyRisk.setManageCompCode(manageCompCode);
        FltdProcess process = new FltdProcess();
        process.setBizGuid(bizGuid);
        List<FltdProcess> fltdProcesses = queryProcessExt1(process);
        List<RiriYyRisk> ririYyRisks = queryYyRisk(ririYyRisk, getUser());
        //判断本部门是否存在违反《经营投资纪律》的情况:为“是” 且数据为空
        if (ririYyRisks.size() == 0 && ("1").equals(fltdProcesses.get(0).getExt1())) {
            return false;
        }
        RiriImpRisk ririImpRisk = new RiriImpRisk();
        ririImpRisk.setAcctYear(acctYear);
        ririImpRisk.setQuarterCurrent(quarterCode);
        ririImpRisk.setDeptCode(deptCode);
        ririImpRisk.setManageCompCode(manageCompCode);
        List<RiriImpRisk> ririImpRisks = queryImpRisk(ririImpRisk,getUser());
        String ext3 = fltdProcesses.get(0).getExt3();
        RiriRiskVO ririRisk = new RiriRiskVO();
        ririRisk.setAcctYear(acctYear);
        ririRisk.setQuarterCurrent(quarterCode);
        ririRisk.setDeptCode(deptCode);
        ririRisk.setManageCompCode(manageCompCode);
        ririRisk.setDetailType("YY98");
        List<RiriRisk> ririRisks = selectRiriRisk(ririRisk, getUser());
        if (ext3.length() > 2) {
            String substring = ext3.substring(1, ext3.length() - 1);
            String[] strArray = substring.split(",");
            String[] nArray = new String[strArray.length];
            for (int i = 0; i < strArray.length; i++) {
                nArray[i] = strArray[i].trim();
            }
            if (ririRisks.size() == 0 && Arrays.asList(nArray).contains("0") && fltdProcesses.get(0).getExt2() != "0"){
                return false;
            }
        }

        //本部门是否存在经营风险事件 选中的”是“且数据为空
        if (ririImpRisks.size() == 0 && "1".equals(fltdProcesses.get(0).getExt2())){
            return false;
        }

        return true;
    }
}
